package com.tiantong.aibilian;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ToastUtils;
import com.mt.mtloadingmanager.LoadingDialog;
import com.mt.mtloadingmanager.LoadingManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tiantong.aibilian.R;

import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.function.Consumer;

import adapter.BleAdapter;
import util.CRC;
import util.ExcelUtil;
import util.HexUtil;
import util.HttpClient;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ble_tag";
    ProgressBar pbSearchBle;
    ImageView ivSerBleStatus;
    TextView tvSerBleStatus;
    TextView tvSerBindStatus;
    ListView bleListView;
    private LinearLayout operaView;
    private LinearLayout myview;
    private Button btnWrite;
    private Button btnRead;
    private EditText etWriteContent;
    private EditText tvResponse;
    private List<BluetoothDevice> mDatas;
    private List<Integer> mRssis;
    private BleAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private boolean isScaning = false;
    private boolean isConnecting = false;
    private BluetoothGatt mBluetoothGatt;

    //服务和特征值
    private UUID write_UUID_service;
    private UUID write_UUID_chara;
    private UUID read_UUID_service;
    private UUID read_UUID_chara;
    private UUID notify_UUID_service;
    private UUID notify_UUID_chara;
    private UUID indicate_UUID_service;
    private UUID indicate_UUID_chara;
    private String hex = "7B46363941373237323532443741397D";
    private ListView mybox;
    private String uuid = "0000fff0-0000-1000-8000-00805f9b34fb";
    private String readuuid = "0000fff1-0000-1000-8000-00805f9b34fb";
    private String writeuuid = "0000fff2-0000-1000-8000-00805f9b34fb";
    private StringBuffer sb = new StringBuffer();
    private String filePaths = "";
    private Dictionary<Integer, List<String>> typelist = new Hashtable<>();
    private List<String> Columns = new ArrayList<>();
    private List<String[]> body = new ArrayList<>();
    private LoadingManager loadingManager;
    private Date mydate;
    private String url="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_device);


        initView();
        initData();
        checkPermissions();
        mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 0);
        }

    }


    private void initData() {
        mDatas = new ArrayList<>();
        mRssis = new ArrayList<>();
        mAdapter = new BleAdapter(MainActivity.this, mDatas, mRssis);
        bleListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();


        typelist.put(1, new ArrayList<String>() {
            {
                this.add("瞬时流量");
                this.add("累计流量");

            }
        });
        typelist.put(2, new ArrayList<String>() {
            {
                this.add("液位");
                this.add("液位温度");

            }
        });
        typelist.put(3, new ArrayList<String>() {
            {
                this.add("变送器温度");


            }
        });
        typelist.put(4, new ArrayList<String>() {
            {
                this.add("压力");


            }
        });
        typelist.put(5, new ArrayList<String>() {
            {
                this.add("温度");


            }
        });


    }

    private void initView() {
        pbSearchBle = findViewById(R.id.progress_ser_bluetooth);
        ivSerBleStatus = findViewById(R.id.iv_ser_ble_status);
        tvSerBindStatus = findViewById(R.id.tv_ser_bind_status);
        tvSerBleStatus = findViewById(R.id.tv_ser_ble_status);
        bleListView = findViewById(R.id.ble_list_view);
        operaView = findViewById(R.id.opera_view);
        myview = findViewById(R.id.myview);
        btnWrite = findViewById(R.id.btnWrite);
        btnRead = findViewById(R.id.btnRead);
        etWriteContent = findViewById(R.id.et_write);
        tvResponse = findViewById(R.id.tv_response);
//
        loadingManager = new LoadingManager(this);
        mybox = findViewById(R.id.mybox);


        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readData();
            }
        });

        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行写入操作

            }
        });


        ivSerBleStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isScaning) {
                    tvSerBindStatus.setText("停止搜索");
                    stopScanDevice();
                } else {
                    scanDevice();
                    //  checkPermissions();
                }

            }
        });
        bleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (isScaning){
//                    stopScanDevice();
//                }
                if (!isConnecting) {
                    isConnecting = true;
                    BluetoothDevice bluetoothDevice = mDatas.get(position);
                    //连接设备
                    tvSerBindStatus.setText("连接中");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this,
                                true, gattCallback, TRANSPORT_LE);
                    } else {
                        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this,
                                true, gattCallback);
                    }
                }

            }
        });


    }


    private void readData() {
        BluetoothGattCharacteristic characteristic = mBluetoothGatt.getService(read_UUID_service)
                .getCharacteristic(read_UUID_chara);
        mBluetoothGatt.readCharacteristic(characteristic);

        mBluetoothGatt.setCharacteristicNotification(characteristic, true);
    }


    /**
     * 开始扫描 10秒后自动停止
     */
    private void scanDevice() {
        tvSerBindStatus.setText("正在搜索");
        isScaning = true;
        pbSearchBle.setVisibility(View.VISIBLE);
        mBluetoothAdapter.startLeScan(scanCallback);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //结束扫描
                mBluetoothAdapter.stopLeScan(scanCallback);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isScaning = false;
                        pbSearchBle.setVisibility(View.GONE);
                        tvSerBindStatus.setText("搜索已结束");
                    }
                });
            }
        }, 100000);
    }

    /**
     * 停止扫描
     */
    private void stopScanDevice() {
        isScaning = false;
        pbSearchBle.setVisibility(View.GONE);
        mBluetoothAdapter.stopLeScan(scanCallback);
    }


    BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            Log.e(TAG, "run: scanning...");
            String name = device.getName();

            if (name != null) {

                if (!mDatas.contains(device) && name.toString().indexOf(("00")) >= 0) {
                    mDatas.add(device);
                    mRssis.add(rssi);
                    mAdapter.notifyDataSetChanged();
                }

            }


        }
    };

    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {


        /**
         * 断开或连接 状态发生变化时调用
         * */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            Log.e(TAG, "onConnectionStateChange()");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //连接成功
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    Log.e(TAG, "连接成功");
                    //发现服务
                    gatt.discoverServices();
                }
            } else {
                //连接失败
                Log.e(TAG, "失败==" + status);
                mBluetoothGatt.close();
                isConnecting = false;
            }
        }

        /**
         * 发现设备（真正建立连接）
         * */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            //直到这里才是真正建立了可通信的连接
            isConnecting = false;
            Log.e(TAG, "onServicesDiscovered()---建立连接");
            //获取初始化服务和特征值
            initServiceAndChara();
            //订阅通知


            BluetoothGattService bluetoothGattService = mBluetoothGatt.getService(UUID.fromString(uuid));

            BluetoothGattCharacteristic notifyCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString(readuuid));

            boolean isEnableNotification = gatt.setCharacteristicNotification(notifyCharacteristic, true);
            System.out.println("isEnableNotification" + isEnableNotification);


//            BluetoothGattCharacteristic characteristic=mBluetoothGatt
//                    .getService(notify_UUID_service).getCharacteristic(notify_UUID_chara);
//            boolean isEnableNotification =  mBluetoothGatt.setCharacteristicNotification(characteristic,true);
//            System.out.println("isEnableNotification"+isEnableNotification);
//
//
//            if(isEnableNotification) {
//                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
//                if(descriptorList != null && descriptorList.size() > 0) {
//                    for(BluetoothGattDescriptor descriptor : descriptorList) {
//                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//                        mBluetoothGatt.writeDescriptor(descriptor);
//                    }
//                }
//            }


            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bleListView.setVisibility(View.GONE);
                    myview.setVisibility(View.VISIBLE);
                    final String[] data = new String[]{"测试通信", "下载数据", "导出文件", "打开文件","复制文件地址"};
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);
                    mybox.setAdapter(adapter);
                    mybox.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                            if (position == 0) {

                                String ss = "0301";
                                String crcstr = CRC.getCRC16(ss).toUpperCase();
                                writeData(ss + crcstr);
                            } else if (position == 1) {
                                mydate = new Date();
                                loadingManager.show();
                                String ss = "0303";
                                String crcstr = CRC.getCRC16(ss).toUpperCase();
                                writeData(ss + crcstr);

                            } else if (position == 2) {

                                if (Columns.size() == 0 ) {
                                    Toast.makeText(MainActivity.this, "请先下载数据", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                String excelFileName = "/设备数据" + System.currentTimeMillis() + ".xls";
                                String sheetName = "demoSheetName";

                                File file = new File(MainActivity.this.getExternalFilesDir(null).getPath() + "/" + excelFileName);

                                filePaths = file.getPath();

                                ExcelUtil.initExcel(filePaths, sheetName, Columns);
                                ExcelUtil.writeObjListToExcel(body, filePaths, MainActivity.this);


                                HttpClient.uploadFile("https://mall.tiantong369.com/upload/file",file,mHandler,2);


                            } else if (position == 3) {

                                if (filePaths.equals("")) {

                                    Toast.makeText(MainActivity.this, "请先导出文件", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                openFileByApp(MainActivity.this, new File(filePaths));


                            }else if(position==4){

                                if (url.equals("")) {

                                    Toast.makeText(MainActivity.this, "请先导出文件", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                                ClipData  mClipData = ClipData.newPlainText("Label", url);
// 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);


                                Toast.makeText(MainActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                            }


                        }
                    });
                    tvSerBindStatus.setText("已连接");
                    //  stopScanDevice();
                }
            });
        }


        /**
         * 读操作的回调
         * */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);

            final byte[] data = characteristic.getValue();
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    addText(tvResponse,bytes2hex(data));
//                }
//            });
            Log.e(TAG, "onCharacteristicRead()" + HexUtil.encodeHexStr(characteristic.getValue()));
        }

        /**
         * 写操作的回调
         * */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);

            String str = HexUtil.encodeHexStr(characteristic.getValue());
            Log.e(TAG, "onCharacteristicWrite()  status=" + status + ",value=" + HexUtil.encodeHexStr(characteristic.getValue()));
            if (str.equals("03034141")) {

                sb.setLength(0);


                Columns = new ArrayList<>();
                body = new ArrayList<>();


                final Timer timer = new Timer();
                TimerTask timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        Date now = new Date();
                        long diff = now.getTime() - mydate.getTime();
                        long diffSeconds = diff / 1000 % 60;
                        if (diffSeconds > 3) {
                            mHandler.sendEmptyMessage(1);
                            timer.cancel();
                        }
                    }
                };

                //主线程中调用：
                timer.schedule(timerTask, 1000, 1000);


            }
        }

        /**
         * 接收到硬件返回的数据
         * */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.e(TAG, "onCharacteristicChanged()" + characteristic.getValue());
            final byte[] data = characteristic.getValue();
            if (data.length == 8) {
                if (data[0] == 3 && data[1] == 1) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "通信成功", Toast.LENGTH_LONG).show();
                        }
                    });
                }


            } else {
                mydate = new Date();
                sb.append(bytes2hex(data));
            }

//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    //ffff 04 02 00 02  0084  读数据
//                    // ffff 03 10 00 00 02 c1 01  写数据
//                    String result = bytes2hex(data);
//                    addText(tvResponse,result);
//                }
//            });


        }
    };

    /**
     * 检查权限
     */

    private static boolean openFileByApp(Context context, File f) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            //7.0以上需要
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", f);
                intent.setDataAndType(uri, mimetype);
            } else {
                intent.setDataAndType(Uri.fromFile(f), mimetype);
            }
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "打开文件出错，无支持的应用", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    private Handler mHandler = new Handler() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String str = sb.toString();

                    String[] ds = str.split("f011");

                    int errorCount = 0;
                    int dataIndex = -1;
                    int sn = 1;

                    DecimalFormat df = new DecimalFormat("0.00");

                    Columns.add("序号");
                    Columns.add("时间");
                    int  max=0;
                    for (int i = 0; i < ds.length; i++) {
                        int  num = ds[i].length();


                    }

                    for (int i = 0; i < ds.length; i++) {
                        String data = ds[i];
                        if (!data.equals("")) {
                            if (data.length() > 6 && data.length() == 2 * HexUtil.Hex2Int(data.substring(0, 4)) - 4) {
                                if (sn == 1) {
                                    int typeCount = HexUtil.Hex2Int(data.substring(18, 18 + 2));
                                    for (int m = 0; m < typeCount; m++) {
                                        int type = HexUtil.Hex2Int(data.substring(20 + m * 4, (20 + m * 4) + 2));
                                        int count = HexUtil.Hex2Int(data.substring(20 + m * 4 + 2, (20 + m * 4 + 2) + 2));

                                        for (int n = 1; n <= count; n++) {

                                            final int finalN = n;
                                            typelist.get(type).forEach(new Consumer<String>() {

                                                @Override
                                                public void accept(String s) {

                                                    Columns.add(s + finalN);
                                                }
                                            });

                                        }
                                    }
                                    dataIndex = 20 + typeCount * 4;
                                }
                                int cursor = dataIndex;

                                int columnCount = Columns.size();
                                String[] values = new String[columnCount];
                                values[0] = String.valueOf(sn++);
                                values[1] = parseTime(data.substring(4, 4 + 12));
                                try {
                                    for (int k = 2; k < columnCount; k++) {
                                        String cloumnName = Columns.get(k);
                                        if (cloumnName.contains("瞬时流量") || cloumnName.contains("累计流量")) {
                                            int value = HexUtil.Hex2Int(data.substring(cursor, cursor + 8));
                                            values[k] = df.format((float) value / 100);

                                            cursor += 8;
                                        } else if (cloumnName.contains("液位温度")
                                                || cloumnName.contains("变送器温度")
                                                || cloumnName.contains("压力")
                                                || cloumnName.contains("温度")) {
                                            int value = HexUtil.Hex2Int(data.substring(cursor, cursor + 4));
                                            values[k] = df.format((float) value / 100);
                                            cursor += 4;
                                        } else if (cloumnName.contains("液位")) {
                                            int value = HexUtil.Hex2Int(data.substring(cursor, cursor + 4));
                                            values[k] = df.format((float) value / 100);
                                            cursor += 4;
                                        }

                                    }

                                    body.add(values);
                                } catch (Exception ex) {
                                    errorCount++;
                                    //MessageBox.Show("数据解析错误！");
                                }


                            }
                        }

                    }

                    System.out.println(Columns);
                    System.out.println(body);


                    loadingManager.hideSuccess("数据获取成功！", new LoadingDialog.OnDialogDismissedListener() {
                        @Override
                        public void onDialogDismissed() {

                        }
                    });

                    break;
                case 2:
                    //{"code":200,"message":"上传成功","pic":"https://mall.tiantong369.com//uploads/20220728/1658973470123-imgFile","file":"/uploads/20220728/1658973470123-imgFile"}
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        String code = json.getString("code");

                        if (!code.equals("200")) {
                            String message = json.getString("message");
                            Toast.makeText(getApplicationContext(),
                                    message, Toast.LENGTH_SHORT)
                                    .show();

                        } else {
                            url=json.getString("pic");
                            Toast.makeText(MainActivity.this, "导出数据成功", Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception ee){

                    }


                    break;
            }
        }
    };

    private String parseTime(String hex) {

        String year = "20" + HexUtil.Hex2Int(hex.substring(0, 2));
        String monthstr = "";
        String daystr = "";
        String hourstr = "";
        String minutestr = "";
        String secondstr = "";
        int month = HexUtil.Hex2Int(hex.substring(2, 4));
        if (month < 10) {
            monthstr = "0" + month;
        } else {
            monthstr = month + "";
        }
        int day = HexUtil.Hex2Int(hex.substring(4, 6));
        if (day < 10) {
            daystr = "0" + day;
        } else {
            daystr = day + "";
        }

        int hour = HexUtil.Hex2Int(hex.substring(6, 8));
        if (hour < 10) {
            hourstr = "0" + hour;
        } else {
            hourstr = hour + "";
        }
        int minute = HexUtil.Hex2Int(hex.substring(8, 10));
        if (minute < 10) {
            minutestr = "0" + minute;
        } else {
            minutestr = minute + "";
        }
        int second = HexUtil.Hex2Int(hex.substring(10, 12));
        if (second < 10) {
            secondstr = "0" + second;
        } else {
            secondstr = second + "";
        }

        return year + "-" + monthstr + "-" + daystr + " " + hourstr + ":" + minutestr + ":" + secondstr;
    }

    public String padLeft(String src, int len, char ch) {
        int diff = len - src.length();
        if (diff <= 0) {
            return src;
        }
        char[] charr = new char[len];
        System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
        for (int i = src.length(); i < len; i++) {
            charr[i] = ch;
        }
        return new String(charr);
    }

    private void checkPermissions() {
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.request(android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
                .subscribe(new io.reactivex.functions.Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            // 用户已经同意该权限

                            Toast.makeText(MainActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            //  ToastUtils.showLong("用户开启权限后才能使用");
                            Toast.makeText(MainActivity.this, "拒绝授权将无法使用", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    private void initServiceAndChara() {
        List<BluetoothGattService> bluetoothGattServices = mBluetoothGatt.getServices();
        for (BluetoothGattService bluetoothGattService : bluetoothGattServices) {

            //String uuid = "00001800-0000-1000-8000-00805f9b34fb";
            if (bluetoothGattService.getUuid().toString().toUpperCase().equals(uuid.toUpperCase())) {

                List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    int charaProp = characteristic.getProperties();
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        read_UUID_chara = characteristic.getUuid();
                        read_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "read_chara=" + read_UUID_chara + "----read_service=" + read_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                        write_UUID_chara = characteristic.getUuid();
                        write_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "write_chara=" + write_UUID_chara + "----write_service=" + write_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                        write_UUID_chara = characteristic.getUuid();
                        write_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "write_chara=" + write_UUID_chara + "----write_service=" + write_UUID_service);

                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                        notify_UUID_chara = characteristic.getUuid();
                        notify_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "notify_chara=" + notify_UUID_chara + "----notify_service=" + notify_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                        indicate_UUID_chara = characteristic.getUuid();
                        indicate_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "indicate_chara=" + indicate_UUID_chara + "----indicate_service=" + indicate_UUID_service);

                    }
                }

            }


        }
    }

    private void addText(TextView textView, String content) {
        textView.append(content);
        textView.append("\n");
        int offset = textView.getLineCount() * textView.getLineHeight();
        if (offset > textView.getHeight()) {
            textView.scrollTo(0, offset - textView.getHeight());
        }
    }

    private void writeData(String content) {
        BluetoothGattService service = mBluetoothGatt.getService(write_UUID_service);
        BluetoothGattCharacteristic charaWrite = service.getCharacteristic(UUID.fromString(writeuuid));
        byte[] data;
        //     String content=etWriteContent.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            data = HexUtil.hexStringToBytes(content);
        } else {
            data = HexUtil.hexStringToBytes(hex);
        }
        if (data.length > 20) {//数据大于个字节 分批次写入
            Log.e(TAG, "writeData: length=" + data.length);
            int num = 0;
            if (data.length % 20 != 0) {
                num = data.length / 20 + 1;
            } else {
                num = data.length / 20;
            }
            for (int i = 0; i < num; i++) {
                byte[] tempArr;
                if (i == num - 1) {
                    tempArr = new byte[data.length - i * 20];
                    System.arraycopy(data, i * 20, tempArr, 0, data.length - i * 20);
                } else {
                    tempArr = new byte[20];
                    System.arraycopy(data, i * 20, tempArr, 0, 20);
                }
                charaWrite.setValue(tempArr);
                boolean s = mBluetoothGatt.writeCharacteristic(charaWrite);
                System.out.println("s" + s);
            }
        } else {
            charaWrite.setValue(data);
            boolean s = mBluetoothGatt.writeCharacteristic(charaWrite);
            System.out.println("s" + s);
        }
        //   mBluetoothGatt.setCharacteristicNotification(charaWrite, true);


    }

    private static final String HEX = "0123456789abcdef";

    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            // 取出这个字节的高4位，然后与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt((b >> 4) & 0x0f));
            // 取出这个字节的低位，与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt(b & 0x0f));
        }
        return sb.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothGatt.disconnect();
    }
}
